package com.yingpai.fitness.dvp_2_0.common.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.transition.Explode;
import android.transition.Fade;
import android.transition.Slide;
import android.transition.Transition;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.FinalOkgo;
import com.yingpai.fitness.dvp_2_0.common.util.ActivityManager;
import com.yingpai.fitness.dvp_2_0.common.util.Utils;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.statusbar.Status;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/2/6.
 */

public abstract class CommonActivity extends AppCompatActivity {
    private int flag = 1000;
    private TextView title;
    private View back;
    protected Dialog loadingDialog;
    protected FinalOkgo finalOkGo;
    protected RxPermissions rxPermissions;
    protected Context context;
    protected LinearLayout empty;

    @SuppressWarnings("unchecked")
    public <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setAllowEnterTransitionOverlap(true);
            getWindow().setAllowReturnTransitionOverlap(true);
        }
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        if (finalOkGo == null) {
            finalOkGo = new FinalOkgo(this);
        }
        context = this;
    }

    public interface AnimationTransition {
        int EXPLODE = 1; //分解
        int FADE = 2; //淡入淡出
        int SLIDE = 3; //划入划出
    }

    /**
     * 设置动画效果
     *
     * @param animationTransition 动画的类型
     */
    protected void setAnimation(int animationTransition) {
        Transition transition = null;
        switch (animationTransition) {

            case 1:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    transition = new Explode();
                }
                break;
            case 2:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    transition = new Fade();
                }
                break;
            case 3:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    transition = new Slide();
                }
                break;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setEnterTransition(transition.setDuration(500)); // 进入的动画
            getWindow().setExitTransition(transition.setDuration(500)); // 退出的动画
            getWindow().setReturnTransition(transition.setDuration(500)); //  返回的动画
            getWindow().setReenterTransition(transition.setDuration(500)); // 重新进入的动画
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActivityManager.getActivityManager().pushActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActivityManager.getActivityManager().popActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //动画效果
//        setAnimation(AnimationTransition.FADE);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
        init();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        ButterKnife.bind(this);
        init();
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        ButterKnife.bind(this);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    protected void setTitlerBarStatusBarAlpha(int color, ViewGroup titleBar) {
        DrawableCompat.setTint(titleBar.getBackground().mutate(), color);
        Status.with(this)
                .statusBarBackground(color);
    }

    protected void setNavigationViewColor(int color) {
        Status.with(this)
                .navigationBarBackground(color);
    }

    protected int evaluate(float fraction, int startValue, int endValue) {
        int startA = (startValue >> 24) & 0xff;
        int startR = (startValue >> 16) & 0xff;
        int startG = (startValue >> 8) & 0xff;
        int startB = startValue & 0xff;

        int endA = (endValue >> 24) & 0xff;
        int endR = (endValue >> 16) & 0xff;
        int endG = (endValue >> 8) & 0xff;
        int endB = endValue & 0xff;

        return ((startA + (int) (fraction * (endA - startA))) << 24) |
                ((startR + (int) (fraction * (endR - startR))) << 16) |
                ((startG + (int) (fraction * (endG - startG))) << 8) |
                ((startB + (int) (fraction * (endB - startB))));
    }

    /**
     * 启动activity
     *
     * @param cls
     * @param bundle
     */
    public void startActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        ActivityCompat.startActivity(this, intent, ActivityOptionsCompat.makeSceneTransitionAnimation(this).toBundle());
    }

    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        ActivityCompat.startActivity(this, intent, ActivityOptionsCompat.makeSceneTransitionAnimation(this).toBundle());
    }

    public void startFinishActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
        finish();
    }

    public void startFinishActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
    }

    public void finishActivity() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAfterTransition();
        } else {
            finish();
        }
    }

    public void call(String phoneStr) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneStr));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void init() {
        back = findView(R.id.back);
        if (back != null) {
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finishActivity();
                }
            });
        }
        title = (TextView) findView(R.id.title);
        empty = findView(R.id.empty);
        if (empty != null) {
            empty.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initData();
                }
            });
        }
        switch (flag) {
            case Contacts.NORMAL_STATUS:
                Status.with(this)
                        .statusBarBackground(ContextCompat.getColor(this, R.color.normal_status))
                        .navigationBarBackground(ContextCompat.getDrawable(this, R.color.colorNavigation));
                break;
            case Contacts.CONTENT_INVASION_STATUS:
                Status.with(this)
                        .statusBarBackground(ContextCompat.getColor(this, R.color.normal_status))
                        .navigationBarBackground(ContextCompat.getDrawable(this, R.color.colorNavigation))
                        .invasionStatusBar();
//                        .fitsSystemWindowView(findView(R.id.title_bar));
                setAnyBarAlpha(0);
                break;
            case Contacts.DRAWERLAYOUT_STATUS:
                Status.with(this)
                        .navigationBarBackground(ContextCompat.getDrawable(this, R.color.colorNavigation))
                        .invasionStatusBar();
                setDrawerLayoutBarAlpha(0);
                break;
            case Contacts.VIEWPAGER_FRAGMENT_STATUS:
                Status.with(this)
                        .invasionStatusBar()
                        .navigationBarBackground(ContextCompat.getDrawable(this, R.color.colorNavigation));
                break;
            default:
                break;
        }

        initView();
        initData();
    }

    protected abstract void initView();

    protected abstract void initData();

    protected void setDrawerLayoutBarAlpha(int alpha) {
        findView(R.id.status_view).getBackground().mutate().setAlpha(alpha);
        if (findView(R.id.title_bar) != null) {
            findView(R.id.title_bar).getBackground().mutate().setAlpha(alpha);
        }
    }

    protected void setAnyBarAlpha(int alpha) {
        if (findView(R.id.title_bar) != null) {
            findView(R.id.title_bar).getBackground().mutate().setAlpha(alpha);
        }
        Status.with(this)
                .statusBarBackgroundAlpha(alpha);
    }

    /**
     * 设置状态栏标识
     * 在setContentView之前调用
     *
     * @param flag
     */
    protected void setStatusFlag(int flag) {
        this.flag = flag;
    }

    protected void setTitle(String titleStr) {
        if (title != null) {
            title.setText(titleStr);
        }
    }

    /**
     * @param context
     * @param msg     这个不填也行，默认是加载中...
     */
    public void showDialog(Context context, @Nullable String msg) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.dialog_loading_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        if (TextUtils.isEmpty(msg)) {
            tipTextView.setText("加载中...");//
        } else {
            tipTextView.setText(msg);// 设置加载信息
        }


        loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
        loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(true); // 点击加载框以外的区域
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        /**
         *将显示Dialog的方法封装在这里面
         */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.PopWindowAnimStyle);
        if (isValidContext(context)) {
            loadingDialog.show();
        }
    }

    /**
     * 关闭dialog
     */
    public void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing() && isValidContext(this)) {
            loadingDialog.dismiss();
        }
    }


    private boolean isValidContext(Context c) {

        Activity a = (Activity) c;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (a.isDestroyed() || a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        }else{
            if (a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        }
    }



    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public String getAppVersionName() {
        try {
            PackageInfo Info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return Info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

    public int getAppVersionCode() {
        try {
            PackageInfo Info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return Info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return 0;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                View view = getCurrentFocus();
                Utils.hideKeyboard(ev, view, this);//调用方法判断是否需要隐藏键盘
                break;

            default:
                break;
        }
        return super.dispatchTouchEvent(ev);

    }

    @OnClick({})
    public void onViewClicked(View view) {
        if (!Utils.isDoubleClick()) {
            return;
        }
    }

}
